#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ctime>

using namespace std;

typedef struct Poly {
	int *coef;
	int len;
} Poly;

Poly polya, polyb;

Poly poly(int len) {
	Poly tmp;
	tmp.len = len;
	tmp.coef = new int[len];
	for (int i=0; i<len; ++i)
		tmp.coef[i] = rand()%10;
	return tmp;
}

void showPoly(Poly p) {
	bool first = true;
	for (int i=p.len-1; i>=2; --i)
		if (p.coef[i] != 0) {
			if (first) {
				cout << p.coef[i] << "*X^" << i;
				first = false;
			}
			else
				cout << " " << (p.coef[i]>0?'+':'-') << " " << abs(p.coef[i]) << "*X^" << i;
		}

	if (p.len>=2 && p.coef[1] != 0) {
		if (first) {
			cout << p.coef[1] << "*X";
			first = false;
		}
		else
			cout << " " << (p.coef[1]>0?'+':'-') << " " << abs(p.coef[1]) << "*X";
	}

	if (p.len>=1 && p.coef[0] != 0) {
		if (first) {
			cout << p.coef[0];
			first = false;
		}
		else
			cout << " " << (p.coef[0]>0?'+':'-') << " " << abs(p.coef[0]);
	}
	cout << endl;
}

int max(int x, int y) {return x>y?x:y;}

Poly add(Poly x, Poly y) {
	Poly res;
	res.len = max(x.len, y.len);
	res.coef = new int[res.len];
	for (int i=0; i<res.len; ++i)
		res.coef[i] = 0;
	for (int i=0; i<res.len; ++i) {
		if (x.len > i)
			res.coef[i] = x.coef[i];
		if (y.len > i)
			res.coef[i] += y.coef[i];
	}
	return res;
}

Poly minusS(int s, Poly x) {
	Poly res;
	res.len = x.len;
	res.coef = new int[res.len];
	for (int i=0; i<x.len; ++i)
		res.coef[i] = s - x.coef[i];
	return res;
}

Poly minus(Poly x, Poly y) {
	return add(x, minusS(0, y));
}

int main(void)
{
	srand(time(0));

	polya = poly(5);
	cout << "polynomial a:\t";
	showPoly(polya);
	polyb = poly(5);
	cout << "polynomial b:\t";
	showPoly(polyb);
	cout << "add result: \t";
	showPoly(add(polya, polyb));
	cout << "minus result: \t";
	showPoly(minus(polya, polyb));

	return 0;
}
